// -------准备数组--------------
// var shoppingcar = document.querySelector('tbody')

var arr = JSON.parse(localStorage.getItem('buyCar')) || []
// ----------数组去重----------------
function findArr(arr, n) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].id == n.id) {
            return true
        }
    }
    return false
}

var newArr = []
var countArr = []
// ------------数组计数------------
for (var i = 0; i < arr.length; i++) {
    if (findArr(newArr, arr[i]) == false) {
        newArr.push(arr[i])
        countArr.push({
            id: arr[i].id,
            count: 1,
            price: arr[i].price
        })
    } else {
        for (var j = 0; j < countArr.length; j++) {
            if (countArr[j].id == arr[i].id) {
                countArr[j].count++
            }
        }
    }
}

// console.log(arr);
// console.log(newArr)
// console.log(countArr)

// -----头部icon图更改名字-----------
var aDiv = $('.right1')
aDiv.mouseenter(function () {
    $(this).children('i').attr('class', 'iconfont icon-xiala-shang')
})
aDiv.mouseleave(function () {
    $(this).children('i').attr('class', 'iconfont icon-xiala-xia')
})

// ---------渲染----------
//---------数据模拟---------
// var arr = [
//     {
//         id : 1,
//         shop :'廉洁易养殖',
//         images :"https://img.zhuego.com/user/98716/2020/0305/20200305102801418.jpg_220X220.jpg",
//         word :'驱虫药 孕畜可用 厂家直销，安全高效，不伤气血，驱虫体内外寄生虫',
//         oldp : 50,
//         newp : 40,
//         vaule : 1,
//     }
  
// ]
// -------------内容渲染--------------

var str = ''
if(newArr.length == 0){
   
    $('tbody').html(`
    <tr class="tab1">
                    <th colspan="6"><p style ="font-size : 30px;color : red">购物车内暂时没有商品</p></br><a style ="font-size : 30px;color : red"href="../index.html">去购物</a></th>
                </tr>
    `)
    
} else {
    
    newArr.forEach(function(ele,index){
      
        str = ` 
        <tr class="kongde">
        <td>
           
       </td>
        </tr>
   <tr class="tabcon">
      
       <td class="tab2">
           <input type="checkbox" class="inper">
       </td>
       <td class="tab3">
           <a href="#">
               <img alt=""
                   src="${ele.img_src}">
           </a>
           <div>
           <div class="dianpu">
           店铺：<a href="#">方腾制药</a>
           </div>
           </br>
           
           
               <a href="#">
               ${ele.title}
               </a>
           </div>
       </td>
       <td width="130">
           <p><s>${ele.price*1.2}</s></p>
           <p>${ele.price}</p>
           <div class="chu">卖家促销</div>
       </td>
       <td width="80">
           <div  class= "btnbaba">
               <div>
                   <input type="text" class="inpshu" value="${countArr[index].count}" data-id="${ele.id}">
               </div>
               <div class="butfu">
                   <input type="button" value="▲" class="add" data-id="${ele.id}">
                   <input type="button" value="▼" class="reduce" data-id="${ele.id}">
               </div>
           </div>
       </td>
       <td>
           <span  data-id="${ele.id}">${ele.price*countArr[index].count}</span>
       </td>
       <td>
           <span class="delete" data-id="${ele.id}">删除</span>
       </td>
      
   </tr>
       
        `

        var html = $('tbody').html()

        $('tbody').html(html + str)

        


})
}





// -------------删除购物车-----------

// $('table').click(function(ev){
//     if(ev.target.className == 'delete'){
//         var abc = ev.target.parentNode.parentNode
//         abc.remove()
       
//     }
    
// })

// -----------删除全部------------
// $('.deleteAll').click(function(){
//     $('tbody').remove()
// })

// ---------全部按钮----------
var allBtn = $('.btnall,.btnallxia')
var allEr = $(".inper")
var num = 0

allBtn.click(function () {
    allBtn.prop("checked", this.checked); 
    $(".inper").prop("checked", this.checked);

    if (this.checked) {
        num = allEr.length
        $('.jianq').html(num)
       
    } else {
        num = 0
        $('.jianq').html(num)
    }
});
allEr.click(function(){
    
    if(this.checked){
        num++
    } else {
        num--
    }
    if(num == allEr.length){
        allBtn.prop("checked", true)
    }else{
        allBtn.prop("checked", false)
    }
    $('.jianq').html(num)
})
// ---------------加减------------
var aAdd = document.querySelectorAll('.add')
var aReduce = document.querySelectorAll('.reduce')
var aTotal = document.querySelectorAll('.zhen')
// console.log(aAdd);
// console.log(aReduce);
// console.log(aTotal);
var arr2 = []
var arr3 = []
// var count = 0
aAdd.forEach(function (ele, index) {
    ele.onclick = function () {
        arr = JSON.parse(localStorage.getItem('buyCar'))
        arr2 = [...arr]
        newArr = []
        countArr = []
        for (var i = 0; i < arr.length; i++) {
            if (findArr(newArr, arr[i]) == false) {
                newArr.push(arr[i])
                countArr.push({
                    id: arr[i].id,
                    count: 1,
                    price: arr[i].price
                })
            } else {
                for (var j = 0; j < countArr.length; j++) {
                    if (countArr[j].id == arr[i].id) {
                        countArr[j].count++
                    }
                }
            }
            // console.log(ele);
        }
        
        for (var i = 0; i < newArr.length; i++) {
            if (ele.getAttribute('data-id') == newArr[i].id) {
                arr2.push(newArr[i])
            }
        }
        arr = [...arr2]
        localStorage.setItem('buyCar', JSON.stringify(arr))
    //    Number(ele.parentNode.previousElementSibling.children.value)++
    

       ele.parentNode.previousElementSibling.children[0].value++
       ele.parentNode.parentNode.parentNode.nextElementSibling.innerHTML = (ele.parentNode.previousElementSibling.children[0].value* ele.parentNode.parentNode.parentNode.previousElementSibling.children[1].innerHTML).toFixed(2)

            var count5 = 0
            var aInp = document.querySelectorAll('.inper')
            var total = document.querySelector('.subtotal')
            console.log(total);
            for (var i = 0; i < aInp.length; i++) {
                if (aInp[i].checked) {
                  
                    var count4 = aInp[i].parentNode.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML
                    // console.log(count4);
                    count5 = count5 + parseInt(count4)
                }
            }
            
            total.innerHTML= count5.toFixed(2)

        }
    
})
aReduce.forEach(function (ele, index) {
    ele.onclick = function () {
        if (ele.parentNode.previousElementSibling.children[0].value > 1) {
            arr = JSON.parse(localStorage.getItem('buyCar'))
            for (var i = arr.length - 1; i >= 0; i--) {
                if (ele.getAttribute('data-id') == arr[i].id) {
                    arr.splice(i, 1)
                    break;
                }
            }
            localStorage.setItem('buyCar', JSON.stringify(arr))
            
            ele.parentNode.previousElementSibling.children[0].value-- 
            ele.parentNode.parentNode.parentNode.nextElementSibling.innerHTML = (ele.parentNode.previousElementSibling.children[0].value* ele.parentNode.parentNode.parentNode.previousElementSibling.children[1].innerHTML).toFixed(2)


            var count5 = 0
            var total = document.querySelector('.subtotal')
            var aInp = document.querySelectorAll('.inper')
            for (var i = 0; i < aInp.length; i++) {
                if (aInp[i].checked) {
                    var count4 = aInp[i].parentNode.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML
                    // console.log(count4);
                    count5 = count5 + parseInt(count4)
                }
            }
            
            total.innerHTML = count5.toFixed(2)


        } else if (ele.parentNode.previousElementSibling.children[0].value <= 1) {
            ele.parentNode.previousElementSibling.children.value = 1
            alert('商品数量不能再减少了')
        }
    }
})
// 删除
var aDel = document.querySelectorAll('.delete')
aDel.forEach(function (ele, index) {
    ele.onclick = function () {
        if (window.confirm('是否确认删除商品')) {
            ele.parentNode.parentNode.parentNode.removeChild(ele.parentNode.parentNode)
            arr = JSON.parse(localStorage.getItem('buyCar'))

            for (var i = 0; i < arr.length; i++) {
                if (ele.getAttribute('data-id') == arr[i].id) {
                    arr.splice(i, 1)
                    i--
                }
            }
            console.log(arr)
            localStorage.setItem('buyCar', JSON.stringify(arr))
            arr = JSON.parse(localStorage.getItem('buyCar'))
        }
        window.location.reload()
    }
})
var danzongjia = document.querySelectorAll('.zhen')
var zongjia =document.querySelector('.subtotal')

var total = document.querySelector('.subtotal')
var aInp = document.querySelectorAll('.inper')
// console.log(aInp);
aInp.forEach(function (ele, index) {
    ele.onclick = function () {
        var count5 = 0
        for (var i = 0; i < aInp.length; i++) {
            if (aInp[i].checked) {
                var count4 = aInp[i].parentNode.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.children[0].innerHTML
                console.log(count4)
                count5 = count5 + parseInt(count4)
                    console.log(count4);
            }
        }
        total.innerHTML = count5.toFixed(2)
    }
})

  // 全选反选
  var oCheck1 = document.querySelector('.btnall')
  var oCheck2 = document.querySelector('.btnallxia')
  var aInp = document.querySelectorAll('.inper')
//   var num = document.querySelector('#shoppingcartCon #goods .goods3 .s4 b')
  var total = document.querySelector('.subtotal')
  var count = 0
  // 全选框
  oCheck1.onclick = function () {
      var count5 = 0
      var aInp = document.querySelectorAll('.inper')
      if (this.checked) {
          aInp.forEach(function (ele, index) {
              ele.checked = true
              count = aInp.length
              var count4 = ele.parentNode.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.children[0].innerHTML
              count5 = count5 + parseInt(count4)
          })
      } else {
          count5 = 0
          aInp.forEach(function (ele, index) {
              ele.checked = false
              count = 0
          })
      }
      total.innerHTML = count5.toFixed(2)
    //   return false
  }
//   oCheck2.onclick = function () {
//     var count5 = 0
//     var aInp = document.querySelectorAll('.inper')
//     if (this.checked) {
//         aInp.forEach(function (ele, index) {
//             ele.checked = true
//             count = aInp.length
//             var count4 = ele.parentNode.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.children[0].innerHTML
//             count5 = count5 + parseInt(count4)
//         })
//     } else {
//         count5 = 0
//         aInp.forEach(function (ele, index) {
//             ele.checked = false
//             count = 0
//         })
//     }
//     total.innerHTML = count5.toFixed(2)
//     return false
// }